package cn.com.gaobb.service.impl;

import cn.com.gaobb.dto.ResultDTO;
import cn.com.gaobb.entity.TClient;
import cn.com.gaobb.entity.TUser;
import cn.com.gaobb.enums.ProServerEnums;
import cn.com.gaobb.mapper.TClientMapper;
import cn.com.gaobb.mapper.TUserMapper;
import cn.com.gaobb.service.UserService;
import cn.com.gaobb.utils.BeanHelper;
import cn.com.gaobb.utils.DataUtil;
import cn.com.gaobb.utils.IdBuilderUtil;
import cn.com.gaobb.utils.JwtUtil;
import cn.com.gaobb.vo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private TUserMapper userMapper;
    @Autowired
    private TClientMapper clientMapper;

    @Override
    public ResultDTO<ResLoginVO> login(String name, String password) {
        TUser searBean = new TUser();
        searBean.setName(name);
        searBean.setDelete(ProServerEnums.DELENOT.getValue());
        TUser user = userMapper.selectOne(searBean);
        if (DataUtil.isNullOrEmpty(user)) {
            return ResultDTO.errorOf(90001, "用户不存在");
        }
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return ResultDTO.errorOf(90002, "用户名和密码不匹配");
        }
        //封装数据
        ResLoginVO vo = BeanHelper.copyProperties(user, ResLoginVO.class);
        vo.setToken(JwtUtil.createJWT(6000000, user));
        return ResultDTO.okOf(vo);
    }


    @Override
    public Boolean Deduplication(String name) {
        TUser user = new TUser();
        user.setDelete(ProServerEnums.DELENOT.getValue());
        user.setName(name);
        int count = userMapper.selectCount(user);
        if (count > 0) {
            return true;
        }
        return false;
    }

    @Override
    public TUser selectById(String id) {
        TUser user = userMapper.selectByPrimaryKey(id);
        return user;
    }


    @Override
    public ResultDTO<ResIdVO> add(ReqUserAddVO vo) {
        //判断当前用户名是否存在
        TUser searchBean = new TUser();
        searchBean.setName(vo.getName());
       Integer num = userMapper.selectCount(searchBean);
        if(num > 0){
            return ResultDTO.errorOf(4001, "用户名重复");
        }
        TUser tUser = BeanHelper.copyProperties(vo, TUser.class);
        tUser.setId(IdBuilderUtil.getId());
        tUser.setCreateTime(new Date());
        tUser.setModifyTime(new Date());
        tUser.setDelete(1);
        tUser.setPassword(passwordEncoder.encode(vo.getPassword()));
        userMapper.insertSelective(tUser);
        return ResultDTO.okOf(new ResIdVO(tUser.getId()));
    }

    @Override
    public ResultDTO update(ReqUserUpdateVO vo) {
        //判断当前用户名是否存在
        TUser searchBean = new TUser();
        searchBean.setName(vo.getName());
        List<TUser> resList = userMapper.select(searchBean);
        if(!CollectionUtils.isEmpty(resList) && !resList.get(0).getId().equals(vo.getId())){
            return ResultDTO.errorOf(4002, "用户名重复");
        }
        TUser tUser = BeanHelper.copyProperties(vo, TUser.class);
        userMapper.updateByPrimaryKeySelective(tUser);
        return ResultDTO.okOf();
    }

    @Override
    public ResultDTO<ResUserDetailVO> detail(String id) {
        TUser tUser = userMapper.selectByPrimaryKey(id);
        ResUserDetailVO resUserDetailVO = BeanHelper.copyProperties(tUser, ResUserDetailVO.class);
        return ResultDTO.okOf(resUserDetailVO);
    }

    @Override
    public ResultDTO deleteList(ResIdListVO vo) {
        if(CollectionUtils.isEmpty(vo.getIdList())){
            return ResultDTO.errorOf(1001, "请选择要删除的用户信息");
        }
        vo.getIdList().forEach(id->{
            userMapper.deleteByPrimaryKey(id);
        });
        return ResultDTO.okOf();
    }

    @Override
    public ResultDTO<ResPageVO<ResUserDetailVO>> listOfPage(ReqPageVO vo) {
        //查询条件封装
        Example example = new Example(TUser.class);
        Example.Criteria criteria = example.createCriteria();
        List<Integer> list = new ArrayList<>();
        list.add(2);
        list.add(3);
        criteria.andIn("role", list);
        if (!DataUtil.isNullOrEmpty(vo.getSearchParem())) {
            Example.Criteria criteria1 = example.createCriteria();
            criteria1.andLike("name", "%" + vo.getSearchParem().trim() + "%");
            example.and(criteria1);
        }
        //按照修改时间倒序
        example.setOrderByClause("modify_time desc");
        //进行分页
        PageHelper.startPage(vo.getCurrentPage(), vo.getPageSize());
        List<TUser> userList = userMapper.selectByExample(example);
        PageInfo<TUser> pageInfo = new PageInfo<>(userList);
        //结果集封装
        ResPageVO<ResUserDetailVO> resVo = new ResPageVO<>();
        resVo.setCurrentPage(pageInfo.getPageNum());
        resVo.setTotal((int) pageInfo.getTotal());
        List<TUser> tUserList = pageInfo.getList();
        if(CollectionUtils.isEmpty(tUserList)){
            resVo.setRows(new ArrayList<ResUserDetailVO>());
            return ResultDTO.okOf(resVo);
        }
        resVo.setRows(BeanHelper.copyWithCollection(pageInfo.getList(), ResUserDetailVO.class));
        resVo.getRows().forEach(bean->{
            if(bean.getRole() == 2){
                bean.setRoleName("仓库管理员");
            }else if(bean.getRole() == 3){
                bean.setRoleName("订单管理员");
            }
        });
        return ResultDTO.okOf(resVo);
    }

    @Transactional
    @Override
    public ResultDTO<ResIdVO> register(ReqRegisterVO reqVo) {
        ResIdVO resVo = new ResIdVO();
        //对用户名是否存在定义
        if (this.Deduplication(reqVo.getName())) {
            return ResultDTO.errorOf(90003, "用户名存在，请重新输入用户名。");
        }
        if (DataUtil.isNullOrEmpty(reqVo.getPassword())
                || !reqVo.getPassword().equals(reqVo.getConfirmPassword())) {
            return ResultDTO.errorOf(90005, "密码和确认密码不一致，请重新输入。");
        }
        //用户信息初始化
        TUser user = BeanHelper.copyProperties(reqVo, TUser.class);
        user.setId(IdBuilderUtil.getId());
        user.setDelete(ProServerEnums.DELENOT.getValue());
        user.setStatus(ProServerEnums.STASHTG.getValue());
        user.setCreateTime(new Date());
        user.setModifyTime(new Date());
        user.setRole(4);
        user.setPassword(passwordEncoder.encode(reqVo.getPassword()));
        //todo  用户基本信息没有用
        userMapper.insertSelective(user);
        //新增客户信息
        TClient client = new TClient();
        client.setModifyTime(new Date());
        client.setCreateTime(new Date());
        client.setId(IdBuilderUtil.getId());
        client.setPhone(reqVo.getMobile());
        client.setAddress(reqVo.getAddress());
        client.setName(reqVo.getName());
        client.setEmail(reqVo.getEmail());
        clientMapper.insertSelective(client);
        resVo.setId(user.getId());
        return ResultDTO.okOf(resVo);
    }

}
